import { isValidDate } from "./isValidDate"


const _week = ['日', '一', '二', '三', '四', '五', '六']
const _pad2 = (num: number): string => num >= 10 ? String(num) : '0' + num

/**
 * @param date
 * @param strFormat
 * @returns {string | null}
 */
export function dateFormat(
  date?: Date | string | number | undefined | null,
  strFormat = 'YYYY-MM-DD HH:mm:ss',
  defaultValue?: string): string {
  let d: Date
  if (date == null) {
    if (defaultValue === undefined) {
      d = new Date()
    } else {
      return defaultValue
    }
  } else if (Number.isInteger(date)) {
    d = new Date(date)
  } else {
    d = new Date(date)
    if (!isValidDate(date)) {
      if (defaultValue === undefined) {
        d = new Date()
      } else {
        return defaultValue
      }
    }
  }

  return strFormat
    .replace(/YYYY/, '' + d.getFullYear())
    .replace(/YY/, _pad2(d.getFullYear() % 100))
    .replace(/MM/, _pad2(d.getMonth() + 1))
    .replace(/DD/, _pad2(d.getDate()))
    .replace(/W/g, _week[d.getDay()])
    .replace(/HH/, _pad2(d.getHours()))
    .replace(/hh/, _pad2(d.getHours() > 12 ? d.getHours() - 12 : d.getHours()))
    .replace(/mm/, _pad2(d.getMinutes()))
    .replace(/ss/, _pad2(d.getSeconds()))
}
